package com.example.shiwu.util;

import java.util.ArrayList;

public class ByteUtil {
    /**
     * 截取byte数组   不改变原数组
     * @param b 原数组
     * @param off 偏差值（索引）
     * @param length 长度
     * @return 截取后的数组
     */
    public static byte[] subByte(byte[] b,int off,int length){
        byte[] b1 = new byte[length];
        System.arraycopy(b, off, b1, 0, length);
        return b1;
    }


    /**
     *  Ascii转换为字符串
     * @param value
     * @return
     */

    public  static String asciiTransformString(String value) {
        StringBuffer sbu = new StringBuffer();
        String[] chars = value.split(",");
        for (int i = 0; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }


    /**
     *  Ascii转换为字符串
     * @param value
     * @return
     */
    public static String byteTransformAscil(byte[] value){
        StringBuffer sbu = new StringBuffer();
        for (int i = 0; i < value.length; i++) {
            sbu.append((char) Integer.parseInt(String.valueOf(value[i])));
        }
        return sbu.toString();
    }

    /**
     * 截取18， 14 buffer,以18分号为截取点,返回分号index
     * @param b
     * @return
     */
    public static int bByteForSemicolon(byte[] b,int indx){
        int semicolon_inx = 0;
        for (int i = indx; i < b.length; i++) {
            if(b[i] == 59){
                semicolon_inx = i;
                break;
            }
        }
        return semicolon_inx;
    }

    /**
     * ArrayList<Byte>转byte【】
     * @param byteList
     * @return
     */
    public static byte[] convertByteListToArray(ArrayList<Byte> byteList) {
        if (byteList == null) {
            return new byte[0];
        }
        byte[] byteArray = new byte[byteList.size()];
        int index = 0;
        for (Byte b : byteList) {
            if (b == null) {
                // 处理 null 值，例如跳过或抛出异常
                continue; // 或抛出异常
            }
            byteArray[index++] = b;
        }
        return byteArray;
    }
}
